

<!DOCTYPE html>
<html class="writer-html5" lang="zh" >
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>统计数据集合 &mdash; Scrapy 2.3.0 文档</title>
  

  
  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster.custom.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster.bundle.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-shadow.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-punk.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-noir.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-light.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-borderless.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/micromodal.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/sphinx_rtd_theme.css" type="text/css" />

  
  
  
  

  
  <!--[if lt IE 9]>
    <script src="../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
        <script src="../_static/jquery.js"></script>
        <script src="../_static/underscore.js"></script>
        <script src="../_static/doctools.js"></script>
        <script src="../_static/language_data.js"></script>
        <script src="../_static/js/hoverxref.js"></script>
        <script src="../_static/js/tooltipster.bundle.min.js"></script>
        <script src="../_static/js/micromodal.min.js"></script>
    
    <script type="text/javascript" src="../_static/js/theme.js"></script>

    
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="发送电子邮件" href="email.html" />
    <link rel="prev" title="登录" href="logging.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../index.html" class="icon icon-home" alt="Documentation Home"> Scrapy
          

          
          </a>

          
            
            
              <div class="version">
                2.3
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">第一步</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../intro/overview.html">Scrapy一目了然</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/install.html">安装指南</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/tutorial.html">Scrapy 教程</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/examples.html">实例</a></li>
</ul>
<p class="caption"><span class="caption-text">基本概念</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="commands.html">命令行工具</a></li>
<li class="toctree-l1"><a class="reference internal" href="spiders.html">蜘蛛</a></li>
<li class="toctree-l1"><a class="reference internal" href="selectors.html">选择器</a></li>
<li class="toctree-l1"><a class="reference internal" href="items.html">项目</a></li>
<li class="toctree-l1"><a class="reference internal" href="loaders.html">项目加载器</a></li>
<li class="toctree-l1"><a class="reference internal" href="shell.html">Scrapy shell</a></li>
<li class="toctree-l1"><a class="reference internal" href="item-pipeline.html">项目管道</a></li>
<li class="toctree-l1"><a class="reference internal" href="feed-exports.html">Feed 导出</a></li>
<li class="toctree-l1"><a class="reference internal" href="request-response.html">请求和响应</a></li>
<li class="toctree-l1"><a class="reference internal" href="link-extractors.html">链接提取器</a></li>
<li class="toctree-l1"><a class="reference internal" href="settings.html">设置</a></li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">例外情况</a></li>
</ul>
<p class="caption"><span class="caption-text">内置服务</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="logging.html">登录</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">统计数据集合</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#common-stats-collector-uses">常用统计信息收集器使用</a></li>
<li class="toctree-l2"><a class="reference internal" href="#available-stats-collectors">可用的统计信息收集器</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#memorystatscollector">MemoryStatsCollector</a></li>
<li class="toctree-l3"><a class="reference internal" href="#dummystatscollector">DummyStatsCollector</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="email.html">发送电子邮件</a></li>
<li class="toctree-l1"><a class="reference internal" href="telnetconsole.html">远程登录控制台</a></li>
<li class="toctree-l1"><a class="reference internal" href="webservice.html">Web服务</a></li>
</ul>
<p class="caption"><span class="caption-text">解决具体问题</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../faq.html">常见问题</a></li>
<li class="toctree-l1"><a class="reference internal" href="debug.html">调试spiders</a></li>
<li class="toctree-l1"><a class="reference internal" href="contracts.html">蜘蛛合约</a></li>
<li class="toctree-l1"><a class="reference internal" href="practices.html">常用做法</a></li>
<li class="toctree-l1"><a class="reference internal" href="broad-crawls.html">宽爬行</a></li>
<li class="toctree-l1"><a class="reference internal" href="developer-tools.html">使用浏览器的开发人员工具进行抓取</a></li>
<li class="toctree-l1"><a class="reference internal" href="dynamic-content.html">选择动态加载的内容</a></li>
<li class="toctree-l1"><a class="reference internal" href="leaks.html">调试内存泄漏</a></li>
<li class="toctree-l1"><a class="reference internal" href="media-pipeline.html">下载和处理文件和图像</a></li>
<li class="toctree-l1"><a class="reference internal" href="deploy.html">部署蜘蛛</a></li>
<li class="toctree-l1"><a class="reference internal" href="autothrottle.html">AutoThrottle 扩展</a></li>
<li class="toctree-l1"><a class="reference internal" href="benchmarking.html">标杆管理</a></li>
<li class="toctree-l1"><a class="reference internal" href="jobs.html">作业：暂停和恢复爬行</a></li>
<li class="toctree-l1"><a class="reference internal" href="coroutines.html">协同程序</a></li>
<li class="toctree-l1"><a class="reference internal" href="asyncio.html">asyncio</a></li>
</ul>
<p class="caption"><span class="caption-text">扩展Scrapy</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="architecture.html">体系结构概述</a></li>
<li class="toctree-l1"><a class="reference internal" href="downloader-middleware.html">下载器中间件</a></li>
<li class="toctree-l1"><a class="reference internal" href="spider-middleware.html">蜘蛛中间件</a></li>
<li class="toctree-l1"><a class="reference internal" href="extensions.html">扩展</a></li>
<li class="toctree-l1"><a class="reference internal" href="api.html">核心API</a></li>
<li class="toctree-l1"><a class="reference internal" href="signals.html">信号</a></li>
<li class="toctree-l1"><a class="reference internal" href="exporters.html">条目导出器</a></li>
</ul>
<p class="caption"><span class="caption-text">其余所有</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../news.html">发行说明</a></li>
<li class="toctree-l1"><a class="reference internal" href="../contributing.html">为 Scrapy 贡献</a></li>
<li class="toctree-l1"><a class="reference internal" href="../versioning.html">版本控制和API稳定性</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">Scrapy</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html" class="icon icon-home"></a> &raquo;</li>
        
      <li>统计数据集合</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="stats-collection">
<span id="topics-stats"></span><h1>统计数据集合<a class="headerlink" href="#stats-collection" title="永久链接至标题">¶</a></h1>
<p>Scrapy提供了一种方便的工具，可以以键/值的形式收集统计信息，其中值通常是计数器。该工具称为stats collector，可以通过 <a class="reference internal" href="api.html#scrapy.crawler.Crawler.stats" title="scrapy.crawler.Crawler.stats"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stats</span></code></a> 的属性 <a class="reference internal" href="api.html#topics-api-crawler"><span class="std std-ref">爬虫API</span></a> ，如中的示例所示 <a class="reference internal" href="#topics-stats-usecases"><span class="std std-ref">常用统计信息收集器使用</span></a> 下面部分。</p>
<p>但是，stats collector始终可用，因此无论stats集合是否启用，您都可以将其导入模块并使用其API（以增加或设置新的stat键）。如果它被禁用，API仍然可以工作，但它不会收集任何东西。这是为了简化StatsCollector的用法：在spider、scrappy扩展名或从中使用StatsCollector的任何代码中，收集统计信息的代码不应超过一行。</p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-1466963416408457"
     data-ad-slot="8850786025"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>StatsCollector的另一个特性是，它在启用时非常高效，在禁用时非常高效（几乎不明显）。</p>
<p>stats收集器为每个打开的spider保留一个stats表，该表在spider打开时自动打开，在spider关闭时关闭。</p>
<div class="section" id="common-stats-collector-uses">
<span id="topics-stats-usecases"></span><h2>常用统计信息收集器使用<a class="headerlink" href="#common-stats-collector-uses" title="永久链接至标题">¶</a></h2>
<p>通过访问Stats Collector <a class="reference internal" href="api.html#scrapy.crawler.Crawler.stats" title="scrapy.crawler.Crawler.stats"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stats</span></code></a> 属性。以下是访问统计信息的扩展示例：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ExtensionThatAccessStats</span><span class="p">:</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">stats</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stats</span> <span class="o">=</span> <span class="n">stats</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">from_crawler</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">crawler</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">cls</span><span class="p">(</span><span class="n">crawler</span><span class="o">.</span><span class="n">stats</span><span class="p">)</span>
</pre></div>
</div>
<p>设置统计值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stats</span><span class="o">.</span><span class="n">set_value</span><span class="p">(</span><span class="s1">&#39;hostname&#39;</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">gethostname</span><span class="p">())</span>
</pre></div>
</div>
<p>增量统计值：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stats</span><span class="o">.</span><span class="n">inc_value</span><span class="p">(</span><span class="s1">&#39;custom_count&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>仅当大于上一个值时设置stat值：：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stats</span><span class="o">.</span><span class="n">max_value</span><span class="p">(</span><span class="s1">&#39;max_items_scraped&#39;</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>仅当低于上一个时设置stat值：：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stats</span><span class="o">.</span><span class="n">min_value</span><span class="p">(</span><span class="s1">&#39;min_free_memory_percent&#39;</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>获取统计值：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="o">.</span><span class="n">get_value</span><span class="p">(</span><span class="s1">&#39;custom_count&#39;</span><span class="p">)</span>
<span class="go">1</span>
</pre></div>
</div>
<p>获取所有统计信息：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="o">.</span><span class="n">get_stats</span><span class="p">()</span>
<span class="go">{&#39;custom_count&#39;: 1, &#39;start_time&#39;: datetime.datetime(2009, 7, 14, 21, 47, 28, 977139)}</span>
</pre></div>
</div>
</div>
<div class="section" id="available-stats-collectors">
<h2>可用的统计信息收集器<a class="headerlink" href="#available-stats-collectors" title="永久链接至标题">¶</a></h2>
<p>除了基本的 <code class="xref py py-class docutils literal notranslate"><span class="pre">StatsCollector</span></code> Scrapy中还有其他可用的统计数据收集器，它们扩展了基本统计数据收集器。您可以通过 <a class="reference internal" href="settings.html#std-setting-STATS_CLASS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATS_CLASS</span></code></a> 设置。使用的默认统计信息收集器是 <code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryStatsCollector</span></code> .</p>
<div class="section" id="memorystatscollector">
<h3>MemoryStatsCollector<a class="headerlink" href="#memorystatscollector" title="永久链接至标题">¶</a></h3>
<dl class="py class">
<dt id="scrapy.statscollectors.MemoryStatsCollector">
<em class="property">class </em><code class="sig-prename descclassname">scrapy.statscollectors.</code><code class="sig-name descname">MemoryStatsCollector</code><a class="reference internal" href="../_modules/scrapy/statscollectors.html#MemoryStatsCollector"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#scrapy.statscollectors.MemoryStatsCollector" title="永久链接至目标">¶</a></dt>
<dd><p>一个简单的统计信息收集器，它在关闭后将上次（每个蜘蛛）抓取运行的统计信息保存在内存中。可以通过 <a class="reference internal" href="#scrapy.statscollectors.MemoryStatsCollector.spider_stats" title="scrapy.statscollectors.MemoryStatsCollector.spider_stats"><code class="xref py py-attr docutils literal notranslate"><span class="pre">spider_stats</span></code></a> 属性，它是由蜘蛛域名键入的dict。</p>
<p>这是Scrapy中使用的默认统计信息收集器。</p>
<dl class="py attribute">
<dt id="scrapy.statscollectors.MemoryStatsCollector.spider_stats">
<code class="sig-name descname">spider_stats</code><a class="headerlink" href="#scrapy.statscollectors.MemoryStatsCollector.spider_stats" title="永久链接至目标">¶</a></dt>
<dd><p>包含每个蜘蛛最后一次抓取运行的统计信息的dict的dict（由蜘蛛名称键控）。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="dummystatscollector">
<h3>DummyStatsCollector<a class="headerlink" href="#dummystatscollector" title="永久链接至标题">¶</a></h3>
<dl class="py class">
<dt id="scrapy.statscollectors.DummyStatsCollector">
<em class="property">class </em><code class="sig-prename descclassname">scrapy.statscollectors.</code><code class="sig-name descname">DummyStatsCollector</code><a class="reference internal" href="../_modules/scrapy/statscollectors.html#DummyStatsCollector"><span class="viewcode-link">[源代码]</span></a><a class="headerlink" href="#scrapy.statscollectors.DummyStatsCollector" title="永久链接至目标">¶</a></dt>
<dd><p>一个只做非常有效的统计数据收集器（因为它什么也不做）。此统计信息收集器可以通过 <a class="reference internal" href="settings.html#std-setting-STATS_CLASS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATS_CLASS</span></code></a> 设置，以禁用统计信息收集以提高性能。但是，与其他零碎的工作负载（如解析页面）相比，统计数据收集的性能损失通常是微乎其微的。</p>
</dd></dl>

</div>
</div>
</div>


           </div>
           
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="email.html" class="btn btn-neutral float-right" title="发送电子邮件" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="logging.html" class="btn btn-neutral float-left" title="登录" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        
        &copy; 版权所有 2008–2020, Scrapy developers
      <span class="lastupdated">
        最后更新于 10月 18, 2020.
      </span>

    </p>
  </div>
    
    
    
    Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a
    
    <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a>
    
    provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
  
 
<script type="text/javascript">
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.1.0";
analytics.load("8UDQfnf3cyFSTsM4YANnW5sXmgZVILbA");
analytics.page();
}}();

analytics.ready(function () {
    ga('require', 'linker');
    ga('linker:autoLink', ['scrapinghub.com', 'crawlera.com']);
});
</script>


</body>
</html>